//
//  MallOrderList.swift
//  LeGou
//
//  Created by lxm on 2022/8/5.
//

import Foundation
import HandyJSON
import UIKit
enum VIPMallOrderType : Int, HandyJSONEnum{
    case all = 0
    case waitPay = 1
    case waitSend = 2
    case waitReceive = 3
    case complete = 4
    case waitConfirm = 5
}

class MallOrderList: ZMViewController, UITableViewDelegate, UITableViewDataSource, ListRequestObjct {
    //MARK: --------------------属性--------------------
    var listData = [VIPMallModels.OrderDetial]()
    var page = 1
    var pageSize = 10
    var refreshScrollView : UIScrollView {
        tableView
    }
    var type : VIPMallOrderType = .all
    
    var orderType = OrdersType.vipMall

    let payHelper = PayHelper()
    //MARK: --------------------UI控件--------------------
    let tableView = UITableView().then { t in
        t.separatorStyle = .none
        t.tableFooterView = UIView()
    }
    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        tableView.mj_header?.beginRefreshing()
    }
    
    //MARK: --------------------UI--------------------
    func setUI() {
        title = ""
        setUpTableView()
        view.backgroundColor = "#F5F5F5".zm.hex()
    }
    
    func setUpTableView() {
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = "#F5F5F5".zm.hex()
        tableView.zm.register(nibName: "MallOrderListCell", reuserId: "MallOrderListCell")
        
        view.addSubview(tableView)
        addRefresh(scrollView: tableView) { [weak self] refresh in
            guard let self = self else {return}
            if refresh {
                self.page = 1
            }
            self.loadList()
        }
        addNodataScrollView(scrollView: tableView)
        emptyTitle = "暂无数据"
        emptyImg = "nodata"
    }
    
    func addConstraints() {
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        ZMPayManager.shard.payCallBack.subscribe(onNext:{ [unowned self] resp in
            switch resp {
            case .success:
                self.tableView.mj_header?.beginRefreshing()
            default:
                ZMToast.showToast(title: resp.rawValue)
            }
        }).disposed(by: disposeBag)
        
        ZMNotification.shard.subject.subscribe(onNext:{ [unowned self] resp in
            switch resp {
            case .refreshOrderList:
                self.tableView.mj_header?.beginRefreshing()
            default:break
            }
        }).disposed(by: disposeBag)
        
        payHelper.paySuccess = { [weak self] in
            guard let self = self else {return}
            self.tableView.mj_header?.beginRefreshing()
        }
    }
    
    func loadList() {
        var pa = ["limit" : pageSize, "page" : page, "type" : type.rawValue]
        if self.orderType != .vipMall {
            pa["orderType"] = self.orderType.rawValue
        }
        ZMUtil.listRequest(type: VIPMallModels.OrderDetial.self, api: VIPMallAPI.orderList(pa)) { resp in
            self.listRequest(resp)
        }
    }
    
    func cancelOrder(id : Int) {
        ZMAlertView.show(title: "提示", content: "是否要取消当前订单", left: "否", right: "是") {
            
        } onRight: {
            ZMToast.showActivity()
            VIPMallAPI.cancelOrder(["id" : id]).rxRequestNullAble(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                self.tableView.mj_header?.beginRefreshing()
            }).disposed(by: self.disposeBag)
        }
    }
    
    //  确认收货
    func ensureReceive(id : Int) {
        ZMAlertView.show(title: "提示", content: "是否确认收货", left: "否", right: "是") {
            
        } onRight: {
            ZMToast.showActivity()
            VIPMallAPI.suerReceive(id).rxRequestNullAble(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                self.tableView.mj_header?.beginRefreshing()
            }).disposed(by: self.disposeBag)
        }
    }
    
    
    func showPay(_ orderNo : String, money : String, orderType : Int) {
        if orderType == 4 {
            self.payHelper.sendPay(currentVC: self, orderNo: orderNo, payType: .integral, info: PwdInputInfo(title: "请输入交易密码", money: money , left: "", right: "", type: 1)) { ok in
                if ok {

                }
            }
        } else {
            let v = ZMUtil.loadNibViewFullScreen(nibName: OrderChoosePayView.self)
            v.price.text = money
            v.payMoney = Double(money) ?? 0
            v.onPayCallback = { [weak self, weak v] type in
                guard let v = v, let self = self else {return}
                
                self.payHelper.sendPay(currentVC: self, orderNo: orderNo, payType: type, info: PwdInputInfo(money: "请输入交易密码", left: "", right: "")) { ok in
                    if ok {
                        v.removeFromSuperview()
                    }
                }
            }
            if orderType == VIPMallModels.OrderType.autoRefund.rawValue {
                v.normalContent.isHidden = true
                v.ckContent.isHidden = true
            }
            APPWindow?.addSubview(v)
        }
    }
    
    // 跳转查看物流
    func goExpress(_ orderNo : String) {
        let vc = ZMLogisticsVC()
        vc.orderNo = orderNo
        navigationController?.pushViewController(vc, animated: true)
    }
    
    //  删除订单
    func ensureDelete(id : Int) {
        ZMAlertView.show(title: "提示", content: "是否要删除当前订单", left: "否", right: "是") {
            
        } onRight: {
            ZMToast.showActivity()
            VIPMallAPI.deleteOrder(id).rxRequestNullAble(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                self.tableView.mj_header?.beginRefreshing()
            }).disposed(by: self.disposeBag)
        }
    }
    
    // 显示课程详情
    func showTheLesson(downloadLink : String, password : String) {
        let v = ZMUtil.loadNibViewFullScreen(nibName: LessonDetailView.self)
        v.downloadLink = downloadLink
        v.password = password
        v.resetUI()
        APPWindow?.addSubview(v)
    }
    
    @objc func selectAddress(orderId : String) {
        let vc = ZMAddressListVC()
        vc.chooseAddressBlockNopush = { [unowned self] address in
            ZMAlertView.show(title: "提示", content: "您是否确认选择该收货地址？", left: "取消", right: "确认") {
                
            } onRight: {
                self.navigationController?.popViewController(animated: true)
                self.onSureAddress(orderId: orderId, address: address)
            }
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func onSureAddress(orderId : String, address : AddressModel) {
        // 确认收货地址
        ZMToast.showActivity()
        VIPMallAPI.ensureAddress(["addressId" : address.id, "orderId" : orderId]).rxRequestNullAble(type: Any.self).subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            self.tableView.mj_header?.beginRefreshing()
        }).disposed(by: disposeBag)
    }
    
    //MARK: --------------------delegate--------------------
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableView.mj_footer?.isHidden = listData.count == 0
        return listData.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data = listData[indexPath.row]
        router.push("xm://main/VIPMall/order_detail", context: ["orderNo" : data.orderId])
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MallOrderListCell") as! MallOrderListCell
        let data = listData[indexPath.row]
        cell.orderNo.text = "订单号：\(data.orderId)"
        if let goods = data.orderInfoList.first {
            cell.img.zm.setImage(urlStr: goods.image)
            cell.name.text = goods.storeName
            cell.time.text = data.createTime
        }
        cell.topLeftIcon.isHidden = data.orderType != .compound
        if orderType == .integral {
            cell.price.text = data.payIntegral.zm.toString(keep: 2) + "积分"
//            cell.price.font = UIFont.systemFont(ofSize: 14, weight: .regular)
            cell.unit.isHidden = true
        } else {
            cell.price.text = data.payPrice.zm.toString(keep: 2)
            cell.unit.isHidden = false
        }
        cell.state.text = data.showStatus.des().title
        cell.state.textColor = data.showStatus.des().color
        cell.icon.isHidden = data.orderType != .auction
        let isIntegral = data.orderType == .integral
        switch data.showStatus {
        case .unpay :
            cell.rightBtn.isHidden = false
            cell.leftBtn.setTitle("取消订单", for: .normal)
            cell.leftBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                self.cancelOrder(id: data.id)
            }).disposed(by: cell.disposeBag)
            
            cell.rightBtn.layer.borderWidth = 0
            cell.rightBtn.backgroundColor = Style.mainColor
            cell.rightBtn.setTitle("立即\(isIntegral ? "兑换" : "付款")", for: .normal)
            cell.rightBtn.setTitleColor(.white, for: .normal)
            cell.rightBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                let payPrice = data.orderType == .integral ? "\(data.payIntegral.zm.toString(keep: 2))" : "\(data.payPrice.zm.toString(keep: 2))"
                self.showPay(data.orderId, money: payPrice, orderType: data.orderType.rawValue)
            }).disposed(by: cell.disposeBag)
        case .waitConfirm:
            cell.rightBtn.isHidden = false
            cell.rightBtn.setTitle("确认收货地址", for: .normal)
            cell.leftBtn.isHidden = true
            cell.rightBtn.setTitleColor(.white, for: .normal)
            cell.rightBtn.layer.borderWidth = 0
            cell.rightBtn.backgroundColor = Style.mainColor
            cell.rightBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                // 确认收货地址
                self.selectAddress(orderId: data.orderId)
            }).disposed(by: cell.disposeBag)
        case .waitSend:
            cell.rightBtn.isHidden = true
            cell.leftBtn.setTitle("联系客服", for: .normal)
            cell.leftBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                CommonService.shared.showContactService()
            }).disposed(by: cell.disposeBag)
        case .waitReceive:
            cell.rightBtn.isHidden = false
            if data.orderType == .lesson {
                // 知识付费
                cell.leftBtn.setTitle("查看课程", for: .normal)
                cell.leftBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                    self.showTheLesson(downloadLink: data.downloadLink, password: data.password)
                }).disposed(by: cell.disposeBag)
            } else {
                cell.leftBtn.setTitle("查看物流", for: .normal)
                cell.leftBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                    self.goExpress(data.orderId)
                }).disposed(by: cell.disposeBag)
            }
            cell.rightBtn.layer.borderWidth = 0.5
            cell.rightBtn.layer.borderColor = Style.mainColor.cgColor
            cell.rightBtn.backgroundColor = .white
            cell.rightBtn.setTitle("确认收货", for: .normal)
            cell.rightBtn.setTitleColor(Style.mainColor, for: .normal)
            cell.rightBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                self.ensureReceive(id: data.id)
            }).disposed(by: cell.disposeBag)
        case .complete:
            cell.rightBtn.isHidden = false
            if data.orderType == .lesson {
                // 知识付费
                cell.leftBtn.setTitle("查看课程", for: .normal)
                cell.leftBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                    self.showTheLesson(downloadLink: data.downloadLink, password: data.password)
                }).disposed(by: cell.disposeBag)
            } else {
                cell.leftBtn.setTitle("联系客服", for: .normal)
                cell.leftBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                    CommonService.shared.showContactService()
                }).disposed(by: cell.disposeBag)

            }
            cell.rightBtn.layer.borderWidth = 0.5
            cell.rightBtn.layer.borderColor = UIColor.zm.colorCCCCCC().cgColor
            cell.rightBtn.backgroundColor = .white
            cell.rightBtn.setTitle("删除订单", for: .normal)
            cell.rightBtn.setTitleColor(UIColor.zm.color333333(), for: .normal)
            cell.rightBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                self.ensureDelete(id : data.id)
            }).disposed(by: cell.disposeBag)
        }
        return cell
    }
}

